include("${CMAKE_CURRENT_LIST_DIR}/RealmTargets.cmake")

# Find dependencies
include(CMakeFindDependencyMacro)

set(REALM_FORCE_OPENSSL @REALM_HAVE_OPENSSL@)
if(REALM_FORCE_OPENSSL)
    if(VCPKG_TOOLCHAIN)
        # If we're building with vcpkg, prefer to find OpenSSL there first
        if(Realm_FIND_QUIETLY)
            set(_quiet_arg QUIET)
        endif()
        find_package(OpenSSL @OPENSSL_VERSION_MAJOR_MINOR@ ${_quiet_arg})
    endif()
    # We aren't building with vcpkg, or it didn't have OpenSSL
    if(NOT OpenSSL_FOUND)
        if(ANDROID OR (CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64"))
            # We have prebuilt OpenSSL tarballs for Android and Linux x86_64
            set(_realm_have_prebuilt_openssl ON)
        endif()
        if(NOT REALM_USE_SYSTEM_OPENSSL AND _realm_have_prebuilt_openssl)
            # Use our own prebuilt OpenSSL
            if(NOT OpenSSL_DIR)
                if(NOT EXISTS ${CMAKE_BINARY_DIR}/openssl/lib/cmake/OpenSSL/OpenSSLConfig.cmake)
                    if(ANDROID)
                        set(OPENSSL_URL "http://static.realm.io/downloads/openssl/@OPENSSL_VERSION@/Android/${CMAKE_ANDROID_ARCH_ABI}/openssl.tar.gz")
                    else()
                        set(OPENSSL_URL "http://static.realm.io/downloads/openssl/@OPENSSL_VERSION@/Linux/x86_64/openssl.tar.gz")
                    endif()

                    message(STATUS "Getting ${OPENSSL_URL}...")
                    file(DOWNLOAD "${OPENSSL_URL}" "${CMAKE_BINARY_DIR}/openssl/openssl.tar.gz" STATUS download_status)

                    list(GET download_status 0 status_code)
                    if (NOT "${status_code}" STREQUAL "0")
                        message(FATAL_ERROR "Downloading ${OPENSSL_URL}... Failed. Status: ${download_status}")
                    endif()
                    message(STATUS "Uncompressing OpenSSL...")
                    execute_process(
                        COMMAND ${CMAKE_COMMAND} -E tar xfz "openssl.tar.gz"
                        WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/openssl"
                    )
                endif()

                set(OpenSSL_DIR "${CMAKE_BINARY_DIR}/openssl/lib/cmake/OpenSSL")
            endif()
            find_package(OpenSSL REQUIRED CONFIG)
            target_link_libraries(OpenSSL::SSL INTERFACE OpenSSL::Crypto)
        else()
            find_dependency(OpenSSL @OPENSSL_VERSION_MAJOR_MINOR@)
        endif()
    endif()
endif()

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_dependency(Threads)

# Use Zlib for Sync, but allow integrators to override it
# Don't use find_library(ZLIB) on Apple platforms - it hardcodes the path per platform,
# so for an iOS build it'll use the path from the Device plaform, which is an error on Simulator.
# Just use -lz and let Xcode figure it out
if(TARGET Realm::Sync AND NOT APPLE AND NOT TARGET ZLIB::ZLIB)
    find_dependency(ZLIB)
endif()